在我看来是remove duplicated elements from sorted array的姊妹题。
给定一个数组(未排序)和一个元素,要求从数组中去除这个元素并返回数组长度。超出数组长度的部分不在考虑范围内。
Description
解题思路:
利用两个指针,一个用来遍历整个数组,如果与给定的元素不相同,则利用另一个index下标将该元素加入到nums数组中。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16def removeElement(self, nums, val):
    """
    :type nums: List[int]
    :type val: int
    :rtype: int
    """
    if not nums:
        return 0
    
    index = 0
    for i in range(len(nums)):
        if nums[i] != val:
            nums[index] = nums[i]
            index += 1
                    
    return index
另外看见一个比较特别的解法:1
2
3
4
5
6def removeElement(self, nums, val):
    try:
        while True:
            nums.remove(val)
    except:
        return len(nums)